<template>
  <drawer placement="right" width="300" :closable="false" :visible="visible">
    <template v-slot:handle>
      <div class="setting-drawer-setting_icon" @click="closeSetting">
        <a-icon :type="visible ? 'close' : 'skin'"></a-icon>
      </div>
    </template>
    <a-spin
      :spinning="loading">
      <div :style="{ marginBottom: '24px' }">
        <h3 class="setting-drawer-index-title">主题色</h3>
        <div style="height: 20px">
          <tooltip
            class="setting-drawer-theme-color-colorBlock"
            v-for="(item, index) in colorList"
            :key="item.key + index"
          >
            <template slot="title">
              {{ item.key }}
            </template>
            <tag :color="item.color" class="setting-drawer-tag-block" @click="changeColor(item.color)">
              <a-icon type="check" v-if="item.color === primaryColor"></a-icon>
            </tag>
          </tooltip>
        </div>
      </div>
      <el-divider/>
      <div :style="{ marginBottom: '24px' }">
        <h3 class="setting-drawer-index-title">透明度</h3>
        <el-slider :debounce="600" :step="0.1" :show-tooltip="false" :value="opacity" @input="opacityValueChange"
                   :max="1"></el-slider>
      </div>
      <div :style="{ marginBottom: '24px' }">
        <h3 class="setting-drawer-index-title">默认背景</h3>
        <div class="setting-drawer-theme-image-bg">
          <div
            :class="['theme-image-bg-item', bgPath === index ? 'border-select' : '']"
            v-for="(bgItem, index) in staticbg"
            :key="'staticbg' + index"
            @click="changeBg(index)">
            <el-image :src="bgItem.src" fit="fill" alt="dark"/>
            <div class="setting-drawer-image-bg-selectIcon" v-if="bgPath === index">
              <a-icon type="check"/>
            </div>
          </div>
        </div>
      </div>
      <div :style="{ marginBottom: '24px' }">
        <h3 class="setting-drawer-index-title">自定义背景</h3>
        <div style="display: flex;flex-wrap: wrap">
          <div :class="['http-image-bg-item' ,isSelectHttp ? 'border-select' : '']"
               @click="changeBg(httpPath)"
               v-if="httpPath">
            <el-image
              fit="cover"
              :src="httpPath"
              class="el-upload-clz-img">
              <a-spin slot="placeholder" :spinning="true" tip="加载中..."/>
            </el-image>
            <div class="setting-drawer-image-bg-selectIcon" v-show="isSelectHttp">
              <a-icon type="check"/>
            </div>
          </div>
          <el-upload
            ref="uploadRef"
            :action="apiUpload"
            :show-file-list="false"
            :limit="1"
            :on-success="uploadSuccess"
            :headers="{
            'Authorization': token
          }"
            :on-error="()=> {
            this.loading = false
            this.$message.error('上传失败')
          }"
            :before-upload="beforeAvatarUpload">
            <el-button class="el-upload-clz">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-button>
          </el-upload>
        </div>
      </div>
    </a-spin>
  </drawer>
</template>

<script>
  import { updateTheme, colorList } from './settingConfig'
  import drawer from 'ant-design-vue/lib/drawer'
  import 'ant-design-vue/lib/drawer/style'
  import tag from 'ant-design-vue/lib/tag'
  import 'ant-design-vue/lib/tag/style'
  import tooltip from 'ant-design-vue/lib/tooltip'
  import 'ant-design-vue/lib/tooltip/style'
  import { mixin } from '@/mixin'
  import { apiUpload, editReceptionSkin } from '@/api/system/config'
  import { getToken } from '@/utils/auth'

  export default {
    name: 'SettingIndex',
    data() {
      const path = require.context('@/assets/background', false, /\.png|\.jpg$/)
      const staticbg = path.keys().map((t, idx) => ({ src: path(t), id: idx }))
      const token = 'Bearer ' + getToken()
      return {
        visible: false,
        loading: false,
        colorList,
        opacity: 0,
        themeBg: 'dark',
        staticbg,
        apiUpload,
        token
      }
    },
    mixins: [mixin],
    components: {
      drawer,
      tag,
      tooltip
    },
    computed: {
      isSelectHttp() {
        return this.httpPath === this.bgPath
      }
    },
    watch: {
      primaryColor: {
        handler: function(val, oldVal) {
          updateTheme(val)
        },
        immediate: true
      }
    },
    methods: {
      closeSetting() {
        this.visible = !this.visible
        if (this.visible) return
        const params = Object.create(null);
        const reg = /^http|https/
        if (typeof this.bgPath === 'string' && reg.test(this.bgPath)) {
          // 网络图片
          params['skinType'] = 2
          params['skinUrl'] = this.httpPath || ''
        }
        if (typeof this.bgPath === 'number') {
          // 网络图片
          params['skinType'] = 1
          params['defaultStting'] = this.bgPath
        }
        params['skinSubjectColor'] = this.primaryColor
        params['skinTransparency'] = this.opacityValue
        editReceptionSkin(params)
      },
      uploadSuccess(response, file, fileList) {
        if (response.code !== 200) {
          this.refs['uploadRef'].clearFiles()
          return this.$message.error(response.msg || '上传失败')
        }
        const httpbg = response['data']['filePath']
        this.$store.dispatch('app/setHttpBg',httpbg)
        this.$store.dispatch('app/setBg', httpbg)
        this.themeBg = httpbg
        this.loading = false
        this.$refs['uploadRef'].clearFiles()
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpg' || 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 5

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 5MB!')
        }
        this.loading = isJPG && isLt2M
        return isJPG && isLt2M
      },
      opacityValueChange(val) {
        this.opacity = val
        this.$store.dispatch('app/setOpacity', val)
      },
      changeColor(color) {
        if (this.primaryColor !== color) {
          this.$store.dispatch('app/setColor', color)
        }
      },
      changeBg(bg) {
        if (this.themeBg !== bg) {
          this.themeBg = bg
          this.$store.dispatch('app/setBg', bg)
        }
      }
    },
    mounted() {
      this.opacity =  this.opacityValue
    }
  }
</script>

<style lang="less" src="./index.less">
